package com.rednose.videoplayer.activities;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.net.Uri;
import android.view.Menu;
import android.view.MenuItem;

import com.rednose.videoplayer.model.MediaFiles;
import com.rednose.videoplayer.adapters.VideoFoldersAdapter;
import com.rednose.videoplayer.R;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<MediaFiles> mediaFiles = new ArrayList<>();//存储所有的视频文件的model
    private ArrayList<String> allFolderList = new ArrayList<>();//存储所有文件夹的路径
    RecyclerView recyclerView;//用于显示文件夹的RecyclerView
    VideoFoldersAdapter adapter;//用于显示文件夹的适配器
    SwipeRefreshLayout swipeRefreshLayout;//用于刷新

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //检查是否登录
        SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String value = preferences.getString("isLogged","");
        if (!value.equals("OK")) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        }

        this.setTitle("您好，"+preferences.getString("username","")+"！");

        //加载文件夹的RecyclerView和刷新控件
        recyclerView = findViewById(R.id.folders_rv);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_folders);
        showFolders();

        //当刷新控件被刷新时，重新加载文件夹
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                showFolders();
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    //获取所有的视频文件，设置适配器传入文件列表、文件夹列表和上下文
    private void showFolders() {
        mediaFiles = fetchMedia();
        adapter = new VideoFoldersAdapter(mediaFiles, allFolderList, this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,
                RecyclerView.VERTICAL, false));//设置布局管理器
        adapter.notifyDataSetChanged();
    }

    //创建视频文件的model 的列表，同时创建所有allFolderList的列表
    @SuppressLint("Range")
    private ArrayList<MediaFiles> fetchMedia() {
        ArrayList<MediaFiles> mediaFilesArrayList = new ArrayList<>();
        //这里的MediaStore是一个媒体库，用于获取媒体文件的信息
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;//获取视频文件的uri
        //创建游标，用于查询媒体库
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        //如果游标不为空，且游标可以移动到下一行
        if (cursor != null && cursor.moveToNext()) {
            do {
                //获取视频文件的id
                String id = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
                //获取视频文件的标题
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
                //获取视频文件的显示名称
                String displayName = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
                //获取视频文件的大小
                String size = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));
                //获取视频文件的时长
                String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
                //获取视频文件的路径
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
                //获取视频文件的添加日期
                String dateAdded = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED));

                //将获取到的信息存入model
                MediaFiles mediaFiles = new MediaFiles(id, title, displayName, size, duration, path, dateAdded);
                //获取文件夹路径
                String folder = path.substring(0, path.lastIndexOf("/"));//从下标0开始到最后一个"/"的位置
                //将model存入列表
                mediaFilesArrayList.add(mediaFiles);
                //如果文件夹列表中不包含当前文件夹
                if (!allFolderList.contains(folder)) {
                    //将文件夹添加到文件夹列表
                    allFolderList.add(folder);
                }
            } while (cursor.moveToNext());
            //关闭游标
            cursor.close();
        }
        return mediaFilesArrayList;
    }


    @Override
    protected void onResume() {
        super.onResume();
        //检查是否登录
        SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String value = preferences.getString("isLogged","");
        if (!value.equals("OK")) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        }
    }


    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.folder_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.refresh_folders) {
            finish();
            startActivity(getIntent());
        } else if (id == R.id.share_app) {
            Intent share_intent = new Intent();
            share_intent.setAction(Intent.ACTION_SEND);
            share_intent.putExtra(Intent.EXTRA_TEXT, "Check this app via\n" +
                    "https://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName());
            share_intent.setType("text/plain");
            startActivity(Intent.createChooser(share_intent, "Share app via"));
        } else if (id == R.id.play_list) {
            Intent intent = new Intent(MainActivity.this, PlayListActivity.class);
            startActivity(intent);
        } else if (id == R.id.log_out) {
            SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.apply();
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        }
        return true;
    }
}
